package com.suxin.ribbon;

/**
 * @author Tang
 * @classname DynamicProperty
 * @description [  ]
 * @date 2022/9/28 15:18
 */
public class DynamicProperty {

    private String stringValue = null;

    private final CachedValue<Boolean> booleanValue = new CachedValue<Boolean>() {
        @Override
        public Boolean parse(String value) throws Exception {
            return "true".equals(value) ? Boolean.TRUE : Boolean.FALSE;
        }
    };

    private final CachedValue<Integer> integerValue = new CachedValue<Integer>() {
        @Override
        public Integer parse(String value) throws Exception {
            return Integer.parseInt(value);
        }
    };

    private final CachedValue<Double> doubleValue = new CachedValue<Double>() {
        @Override
        public Double parse(String value) throws Exception {
            return Double.parseDouble(value);
        }
    };

    public abstract class CachedValue<T>{

        public abstract T parse(String value) throws Exception;

        public T getValue() {
            try {
                return parse(DynamicProperty.this.stringValue);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        public T getValue(T defaultValue) {
            T value = getValue();
            return value == null ? defaultValue : value;
        }

    }

    public String getStringValue() {
        return stringValue;
    }

    public Boolean getBooleanValue() {
        return booleanValue.getValue();
    }

    public Integer getIntegerValue() {
        return integerValue.getValue();
    }

    public Double getDoubleValue() {
        return doubleValue.getValue();
    }
}
